package com.jumi.microservice.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.jumi.microservice.config.AliSmsConfig;
import com.jumi.microservice.domain.SendSms;
import com.jumi.microservice.service.SmsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

@Service
public class SmsServiceImpl implements SmsService {

    @Resource
    private AliSmsConfig aliSmsConfig;

    @Override
    public String send(SendSms sendSms) {
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-hangzhou",
                aliSmsConfig.getAccessKeyId(),
                aliSmsConfig.getAccessKeySecret()
        );
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", sendSms.getPhoneNumbers());//手机号
        request.putQueryParameter("SignName", aliSmsConfig.getSignName());//短信签名
        request.putQueryParameter("TemplateCode", sendSms.getTemplateCode());//模板id
        request.putQueryParameter("TemplateParam", sendSms.getTemplateParam());//短信模板变量替换参数
        try {
            CommonResponse response = client.getCommonResponse(request);
//            System.out.println(response.getData());
            return response.getData();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }
}
